package com.wing.productionPlan.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;

import com.wing.enterprise.product.model.entity.ProductDetail;
import com.wing.productionPlan.model.entity.ProductionPlan;
import com.wing.productionPlan.model.entity.ProductionPlanRecord;
import com.wing.productionPlan.model.response.*;
import com.wing.productionPlan.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 排产记录-Controller
 *
 * @author xiayang
 */
@Slf4j
@Validated
@Api(value = "排产记录管理", tags = "#/productionRecord/productionRecord")
@RestController("productionRecordController")
@RequestMapping("productionRecord/admin/productionRecord")
@RequiredArgsConstructor
public class ProductionRecordController {

    private final ProductionPlanRecordService productionPlanRecordService;
    private final ProductionWorkOrderService productionWorkOrderService;

    @ApiOperation(value = "查询排产记录", notes = "查询排产记录")
    @GetMapping("/list")
    public PageResult<ProductionPlanRecordVO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            Long productionPlanId, String code, String skuCode,
            String skuSpec, ProductionPlan.OrderType orderType,
            String planSource,
            @RequestParam(name = "startTime",required = false) String startTime,
            @RequestParam(name = "endTime",required = false) String endTime,
            String workshopName,
            String creatorName,
            String startProductTime,
            String productionPlanRecordCode,
            String endProductTime) {
        Page<ProductionPlan> pg = new Page<>(page, limit);
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("productionPlanId", productionPlanId);
        paramMap.put("code", code);
        paramMap.put("customerSkuCode", skuCode);
        paramMap.put("productionPlanRecordCode", productionPlanRecordCode);
        paramMap.put("customerSkuSpec", skuSpec);
        paramMap.put("startCreateTime", startTime);
        paramMap.put("endCreateTime", endTime);
        paramMap.put("workshopName", workshopName);
        paramMap.put("creatorName", creatorName);
        paramMap.put("startProductTime", startProductTime);
        paramMap.put("endProductTime", endProductTime);
        if (orderType != null) {
            paramMap.put("orderType", orderType.getValue());
        }
        paramMap.put("status", ProductionPlan.Status.alreadyrowproduce.getValue());
        if (StringUtils.isNotBlank(planSource)) {
            Integer sourceValue = ProductionPlan.PlanSource.valueOf(planSource).getValue();
            paramMap.put("planSource", sourceValue);
        }
        IPage<ProductionPlanRecordVO> list = productionPlanRecordService.pageList(pg, paramMap);
        List<ProductionPlanRecordVO> records = list.getRecords();
        if (CollectionUtil.isNotEmpty(records)){
            for (ProductionPlanRecordVO record : records) {
                //查询当前制造令 末工序的报工数
                Integer lastReport = this.productionWorkOrderService.getLastReportInfoBy(record.getId());
                record.setLastReportedQuantity(lastReport);

                //查询已排产数量
                QueryWrapper<ProductionPlanRecord> recordQueryWrapper = new QueryWrapper<>();
                recordQueryWrapper.eq("production_plan_id",record.getProductionPlanId());
                recordQueryWrapper.eq("is_deleted",false);
                List<ProductionPlanRecord> planRecords = this.productionPlanRecordService.list(recordQueryWrapper);
                Integer totalQuantity = planRecords.stream()
                        // 过滤掉 productionPlanQuantity 为 null 的对象
                        .filter(product -> product.getProductionPlanQuantity() != null)
                        // 提取出 productionPlanQuantity 并转为 int
                        .mapToInt(ProductionPlanRecord::getProductionPlanQuantity)
                        .sum(); // 进行累加
                record.setProductionPlanHaveQuantity(totalQuantity);
            }
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "终止排产计划", notes = "终止排产计划")
    @PostMapping("/stop")
    public JsonResult stop(@RequestParam(name = "productionPlanId") Long productionPlanId) {
//        productionPlanService.stop(productionPlanId);
        return JsonResult.success("终止成功");
    }

    @ApiOperation(value = "查看排产记录详情", notes = "排产-详情")
    @GetMapping("/detail")
    public JsonResult getRecordDetail(
            @RequestParam(value = "type") String type,
            @RequestParam(value = "productionPlanRecordId") Long productionPlanRecordId,
            @RequestParam(value = "bookId",required = false) Long bookId,
            @RequestParam(value = "processId",required = false)Long processId
    ) {
        return productionPlanRecordService.getRecordDetailBy(type,productionPlanRecordId,bookId,processId);
    }



    @ApiOperation(value = "查看排产物料", notes = "排产-物料")
    @GetMapping("/getMaterialBy")
    public JsonResult getMaterialBy(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(value = "processId") String processId,
            @RequestParam(value = "planRecordId") String planRecordId
             , String skuSpec,  String productTypeId,  String skuName,String skuCode
    ) {
        Page<ProductDetail> pg = new Page<>(page, limit);
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("skuSpec", skuSpec);
        paramMap.put("productTypeId", productTypeId);
        paramMap.put("skuName", skuName);
        paramMap.put("skuCode", skuCode);
        return productionPlanRecordService.getMaterialBy(processId,planRecordId,pg,paramMap);
    }


    @ApiOperation(value = "查看所有物料", notes = "排产-物料")
    @GetMapping("/getMaterialOthers")
    public PageResult<ProductDetail>  getMaterialOthers(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            String skuSpec,  String productTypeId,  String skuName,String skuCode
    ) {
        Page<ProductDetail> pg = new Page<>(page, limit);

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("skuSpec", skuSpec);
        paramMap.put("productTypeId", productTypeId);
        paramMap.put("skuName", skuName);
        paramMap.put("skuCode", skuCode);

        IPage<ProductDetail> list = productionPlanRecordService.getMaterialOthers(pg,paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

}
